<?php

namespace App\Api\Controllers;

use App\Api\Services\MaterielService;
use App\Http\Controllers\Api\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class MaterielController extends BaseController
{
    public function materielInStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'status' => [
                'required',
                Rule::In([1, 2]),
            ],//入库状态：1-全部 2-部分
            'in_storage_time' => 'date_format:Y-m-d H:i:s',//入库时间
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        if(empty($data['content'])) {
            return $this->fail('', '请填写采购内容');
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();

        $this->log('采购单入库', $data);

        return response()->json(
            MaterielService::materielInStorage(
                $data
            )
        );
    }

    /**
     * 采购列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/5/18 16:05
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|numeric|min:1',//页面大小
            'currentPage' => 'required|numeric|min:1',//当前页码
            'search_type'=>[
                'required',
                Rule::In([0,1,2,3,4,5,6,7,8])
            ],
            'status'=>[
                'required',
                Rule::In([0,1,2,3,4,5,6])
            ]
        ],[
            'pageSize.required' => '参数`页面大小`缺失',
            'pageSize.numeric' => '参数`页面大小`仅能为数字',
            'pageSize.min' => '参数`页面大小`最小只能为1',
            'currentPage.required' => '参数`页码`缺失',
            'currentPage.numeric' => '参数`页码`仅能为数字',
            'currentPage.min' => '参数`页码`最小只能为1',
            'search_type.required' => '参数`搜索类型`缺失',
            'search_type.in' => '参数`搜索类型`不合法',
            'status.required' => '参数`状态`缺失',
            'status.in' => '参数`状态`不合法',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(isset($request->start_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'start_time' => 'date_format:Y-m-d H:i:s',//页面
            ],[
                'start_time.date_format' => '开始时间格式错误，例：'.date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        if(isset($request->end_time)) {
            $timeValidator = Validator::make($data = $request->all(), [
                'end_time' => 'date_format:Y-m-d H:i:s',//页面
            ],[
                'end_time.date_format' => '结束时间格式错误，例：'.date('Y-m-d H:i:s')
            ]);

            //参数错误响应
            if ($infos = $timeValidator->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();

        if($this->getUserId() == $this->getMainUserId()){
            $userId['a.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            $userId['a.user_id'] = ['EQ' => $this->getUserId()];
        }

        return $this->success(
            MaterielService::list($data, $userId)
        );
    }

    public function payHistory(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id'=>'required|integer',//销售单主键
        ],[
            'id.required' => '参数`采购单id`是必须的'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            MaterielService::payHistory($request->id)
        );
    }

    public function cancel(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//采购单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(
            MaterielService::cancel(
                $this->getMainUserId(),
                $data
            )
        );
    }
//
//    /**
//     * @新建采购单
//     * created 在 2021/11/23 15:52 创建
//     * updated at 2022/05/25 16:04
//     * @author SunWu
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function add(Request $request)
//    {
//        if(empty($request->materiel_content)) {
//            return $this->fail('', '请添加需采购的物料产品');
//        }
//
//        $info = SELF::checkInput($data = $request->all());
//
//        if($info) {
//            return $info;
//        }
//
//        if(!in_array(empty($request->source)?1:$request->source, [1,2,3,4,5])) {
//            return $this->fail('', '订单来源不合法，请重试');
//        }
//
//        $data['user_id'] = $this->getUserId();
//        $data['main_id'] = $this->getMainUserId();
//        $data['purchase_no'] = SELF::createPurchaseNo();
//
//        $this->log('新建采购单', $data);
//
//        return response()->json(MaterielsService::add($data));
//    }
//
//    //创建采购单号
//    private function createPurchaseNo()
//    {
//        list($t1, $t2) = explode(' ', microtime());
//        $str =(float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
//        $millisecond = substr($str,10,13);
//        $date = date("YmdHis").$millisecond.mt_rand(100000,999999);
//
//        return $date;
//    }
//
//    private function checkInput($data)
//    {
//        //参数验证
//        $validator = Validator::make($data, [
//            'supplier_customer_id' =>'required|integer',//供应商id
//            'purchase_time' => 'required',//采购日期
//            'tax_rate' =>'required|integer|min:0',//税率
//            // 'other_charges' => 'integer|min:0',//其他费用
//            'preferential_way' => [
//                'required',
//                Rule::In([0, 1, 2]),
//            ],//优惠方式;0:无;1:修改价格;2:折扣优惠;
//            'preferential_money' =>'numeric|min:0',//优惠方式对应金额
//        ]);
//
//        //参数错误响应
//        if($info = $validator->errors()->first()) {
//            return response()->json([
//                'code' => 1,
//                'msg' => $info,
//                'data' => '',
//            ]);
//        }
//    }
//
//    /**
//     * @修改采购单
//     * created 在 2021/11/24 14:52 创建
//     * @author SunWu
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function edit(Request $request)
//    {
//        if(empty($request->materiel_content)) {
//            return $this->fail('', '请添加需采购的物料产品');
//        }
//
//        if(empty($request->id) || !is_numeric($request->id)) {
//            return $this->fail('', '参数`id`缺失');
//        }
//
//        $info = SELF::checkInput($data = $request->all());
//
//        if($info) {
//            return $info;
//        }
//
//        $data['user_id'] = $this->getUserId();
//        $data['main_id'] = $this->getMainUserId();
//
//        $this->log('修改采购单', $data);
//        return response()->json(MaterielsService::edit($data));
//    }

}
